package cn.virens.common.boot.rabbit.mqtt;

import cn.virens.common.boot.rabbit.autoconfig.RabbitManageProperties;
import cn.virens.common.util.core.Assert;
import cn.virens.common.util.exception.APIException;
import com.alibaba.fastjson2.JSON;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

public class RabbitMqttServiceImpl implements RabbitMqttService {
    protected final RabbitManageProperties properties;
    protected final RabbitTemplate mRabbitTemplate;

    public RabbitMqttServiceImpl(RabbitManageProperties properties, RabbitTemplate mRabbitTemplate) {
        this.mRabbitTemplate = mRabbitTemplate;
        this.properties = properties;
    }

    @Override
    public void send(String routingKey, Object data) throws APIException {
        this.queueSend(routingKey, JSON.toJSONBytes(data));
    }

    @Override
    public void send0(String routingKey, Message message) throws APIException {
        mRabbitTemplate.send(properties.getExchangeMqtt(), routingKey, message);
    }

    @Override
    public void send0(String routingKey, Message message, CorrelationData correlationData) throws APIException {
        mRabbitTemplate.send(properties.getExchangeMqtt(), routingKey, message, correlationData);
    }

    protected void queueSend(String routingKey, byte[] bytes) throws APIException {
        MessageBuilder builder = MessageBuilder.withBody(Assert.isNull(bytes));
        builder.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        builder.setContentLength(bytes.length);

        this.queueSend(routingKey, builder.build());
    }

    protected void queueSend(String routingKey, Message message) throws APIException {
        this.mRabbitTemplate.send(properties.getExchangeMqtt(), routingKey, message);
    }
}
